package work.huangxin.share.controller.user;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.huangxin.share.constant.ClassScheduleConstant;
import work.huangxin.share.domain.other.*;
import work.huangxin.share.domain.schedule.ClassSchedule;
import work.huangxin.share.domain.schedule.ClassScheduleRequest;
import work.huangxin.share.domain.schedule.ClassScheduleResponse;
import work.huangxin.share.service.ClassScheduleService;
import work.huangxin.share.service.impl.UserMessageOperationService;
import work.huangxin.share.util.*;
import work.huangxin.share.util.common.HttpClientUtil;
import work.huangxin.share.util.common.JsonUtils;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;


@RestController
@RequestMapping("/wx")
@Slf4j
public class LoginController {

    @Resource
    private UserMessageOperationService userMessageOperationService;
    @Resource
    private WXMessage wxMessage;
    @Resource
    private Audience audience;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    @Qualifier("logThreadPool")
    private  ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ParseClassScheduleUtil parseClassScheduleUtil;

    @Autowired
    private ClassScheduleService classScheduleService;


    /**
     * 绑定手机号
     *
     * @param decodePhoneMessage
     * @return
     */
    @PostMapping("/getPhoneNumber")
    @Transactional
    @ApiOperation(value = "绑定手机号")
    public BaseResponse getPhone(@RequestBody DecodePhoneMessage decodePhoneMessage, HttpServletRequest request) {

        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        Long userId = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        UserMessage userMessage = new UserMessage();
        PhoneMessage phoneMessage;

        try {
            phoneMessage = JsonUtils.jsonToPojo(WxGetPhoneUtils.wxDecrypt(decodePhoneMessage.getEncryptedData(),
                    user.getSession_key(), decodePhoneMessage.getIv()), PhoneMessage.class);
            userMessage.setUserToken(user.getOpenid());
            userMessage.setUserId(user.getUserId());
            userMessage.setUserPhone(phoneMessage.getPhoneNumber());
            userMessageOperationService.update(userMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.out(CodeEnum.FAIL, "获取失败");
        }
        return ResponseData.success(phoneMessage);
    }

    /**
     * 登录功能
     */
    @PostMapping("/Login")
    @Transactional
    @ApiOperation(value = "登录")
    public BaseResponse toLogin(String code, @RequestBody UserMessage userMessage) {
        WXSessionModel wxSessionModel = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<>();
        param.put("appid", wxMessage.getWxId());
        param.put("secret", wxMessage.getWxSecret());
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String wxResult = HttpClientUtil.doGet(url, param);
        wxSessionModel = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
        String openid = wxSessionModel.getOpenid();

//        UserMessage tem = new UserMessage();

//        tem.setUserToken(openid);
        userMessage.setUserToken(openid);
        LoginResponse loginResponse = new LoginResponse();
        //新用户登入
        List<UserMessage> list = userMessageOperationService.findList(userMessage);
        if (list.size() == 0) {
            userMessage.setUserMotto("这个人很懒,什么也没有留下");
//            userMessage.setUserToken(openid);
            userMessageOperationService.add(userMessage);

//            tem = new UserMessage();
//            tem.setUserToken(openid);

            wxSessionModel.setUserId(userMessageOperationService.findList(userMessage).get(0).getUserId());
            loginResponse.setUserToken(JWTUtil.createJWT(audience, wxSessionModel));
            loginResponse.setIsBinding(false);
            return ResponseData.success(loginResponse);
        }


        wxSessionModel.setUserId(list.get(0).getUserId());

        userMessage.setUserId(list.get(0).getUserId());

        userMessageOperationService.update(userMessage);
        loginResponse.setUserToken(JWTUtil.createJWT(audience, wxSessionModel));
        loginResponse.setIsBinding(null != list.get(0).getCampusId());

        return ResponseData.success(loginResponse);
    }
    @PostMapping("/binding")
    public BaseResponse bindingCollageInfo(@RequestBody UserMessage userMessage,
                                           HttpServletRequest request){

        if (null == userMessage.getCampusId() || null == userMessage.getAccount() || null == userMessage.getPassword()){
            return ResponseData.error(CodeEnum.BODY_NOT_MATCH);
        }
        //TODO:调用pythonWeb项目获得登入状态，以及班级信息，绑定班级信息，后续通过班级信息得到课表数据
        //从数据中查询user信息
        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        UserMessage userMessage1 = userMessageOperationService.getUserMessage(user.getUserId());
        if (Objects.isNull(userMessage1)){
            return ResponseData.error(404,"用户不存在");
        }
        ClassScheduleRequest classScheduleRequest = new ClassScheduleRequest(userMessage.getAccount(), userMessage.getPassword());
        String requestJSON = JSON.toJSONString(classScheduleRequest);
        log.info("Post请求体为-----》" + requestJSON);
        String resultJson = HttpClientUtil.doPostJson("http://127.0.0.1:5000/login", requestJSON);
        log.info("响应结果为-----》"+ resultJson);
        ClassScheduleResponse classScheduleResponse = JSON.parseObject(resultJson, ClassScheduleResponse.class);
        log.info("解析结果为----》" + classScheduleResponse);
        if(classScheduleResponse.getStatus() == 1){
            return ResponseData.error(403, "请检查教务系统账号密码");
        }
        userMessage1.setCampusId(userMessage.getCampusId());
        userMessage1.setAccount(userMessage.getAccount());
        userMessage1.setPassword(userMessage.getPassword());
        userMessage1.setClazzName(classScheduleResponse.getSpecialty());
        userMessageOperationService.update(userMessage1);
        threadPoolExecutor.execute(() ->{
            //异步解析课表
            //判断课表是否已经存在
            int count = classScheduleService.getClazzName(classScheduleResponse.getSpecialty());
            if (count == 0){
                log.info("开始解析课表----->");
                //需要进行解析课表
                ParseClassScheduleUtil.parseToClassSchedule(ClassScheduleConstant.CLASS_SCHEDULE_PATH+classScheduleResponse.getSpecialty()+".xlsx", classScheduleResponse.getSpecialty());
            }
        });
        return ResponseData.success("绑定用户信息成功");
    }
}
